package pl.un4giv3n.mightvsmagic.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.FightReport;
import pl.un4giv3n.mightvsmagic.entity.User;

/**
 * @author andrzejewskia
 * marks unseen defences from last week as seen
 */
public class MarkReportsAsReadAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	private User user;
	private List<FightReport> fights;
	private boolean showDefenses;
	
	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		Query query = entityManager.createNamedQuery("find.user.unread.defenses");
		query.setParameter("id", getSessionUserId());
		query.setParameter("time", System.currentTimeMillis() - ONE_WEEK);
		fights = query.getResultList();
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		for (FightReport fight : fights) {
			System.out.println("marking as read fight with id="+fight.getId());
			fight.setDefenderSeen(true);
			entityManager.merge(fight);
		}
		entityManager.flush();
		transaction.commit();
		entityManager.close();
		return SUCCESS;
	}
	
	public List<FightReport> getFights() {
		return fights;
	}
	public boolean isShowDefenses() {
		return showDefenses;
	}
	public void setShowDefenses(boolean showDefenses) {
		this.showDefenses = showDefenses;
	}
	
}
